public without sharing class GetExternalDataUtil {
  
  public String objId {get;private set;}


  public Boolean isUpdate {get;private set;} 
  public Boolean isPrice {get;private set;} 

  public String objName {get;private set;}

  public String msg {get;private set;}

	public GetExternalDataUtil(){

      objId = System.currentPageReference().getParameters().get('id');
      objName = System.currentPageReference().getParameters().get('objName');
       isPrice = System.currentPageReference().getParameters().get('price') != null ;
      isUpdate = objId != null;
      System.debug(isUpdate);

	}

  public void init(){

    if(isUpdate){
      msg = '';
      Map<String,String> res = null;
      if(Id.valueOf(objId).getSobjectType() == Account.SObjectType){

         res = getAccountFromNc([select AccountNumber from Account where Id=:objId].AccountNumber);

      }else if(Id.valueOf(objId).getSobjectType() == Product__c.SObjectType){

           Product__c p = [select NCcode__c,Brand__c  from Product__c where Id=:objId];
           if( !isPrice )res = getProductFromNc( p.NCCode__c);
           if( isPrice )res = getCostPrice(p.NCCode__c);
      }
      if(res.get('code') == '1'){
        msg = '更新成功!';
      }else{
        msg = res.get('msg');
      }


    }
  }



  public static Map<String,List<String>> getCompanyProvinceMap(){

      Map<String,List<String>> cpM = new Map<String,List<String>>();
      String cp = '贵州省-贵州迈克科技有限公司,吉林省/辽宁省/黑龙江省-吉林迈克生物有限公司,广东省/海南省-迈克生物（广东）有限公司,湖北省-迈克生物（湖北）有限公司,江西省/湖南省/福建省/广西省/甘青宁/陕西省/河南省-迈克生物股份有限公司,山东省-山东迈克生物科技有限公司,山西省-山西迈克生物有限公司,四川省/西藏|重庆市-四川省迈克实业有限公司,新疆-新疆迈克宏康生物有限公司,云南省-云南迈克科技有限公司,重庆市-重庆征途科技有限公司,北京市/天津市/河北省-北京迈克生物科技有限公司,四川省/西藏/重庆市-迈克医疗电子有限公司,内蒙古-内蒙古迈克生物科技有限公司,安徽省|浙江省|江苏省|上海市-上海迈可优生物科技有限公司';

      for (String cps  : cp.split(',') ) {
          
          List<String> ss = cps.split('-');
          System.debug(ss);
          if(ss.size() > 0 )cpM.put(ss[1], ss[0].split('\\|'));
      }
      return cpM;
  }

  //获取产品的参考成本价
  @RemoteAction
  public static Map<String,String>  getCostPrice(String nccodes ){

      if(nccodes == null ) return setResult(false,'请输入存货编码');

    Boolean isMult = nccodes.contains(',') ;

    String sql1 = '   select unitname ,invcode ,oritaxprice from v_nctosf_pricelista where unitname !=\'迈凯基因科技有限公司\' and unitname != \'四川迈克生物新材料技术有限公司\'  ';

    Set<String> nsets = new Set<String>();

    if(isMult ){

        sql1 += ' and invcode in '+ JSON.serialize(nccodes.trim().split(',')).replaceAll('"','\'').replace('[','(').replace(']',')') ; 
        nsets.addAll(nccodes.trim().split(','));

    }else{

      sql1 += ' and invcode  = \''+nccodes.trim()+'\'';

      nsets.add(nccodes.trim());

    }

      Map<String,String>productMap = new Map<String,String>();

      for (Product__c p  :[select Id ,NCCode__c from Product__c where NCcode__c in: nsets] ) {
          productMap.put(p.NCCode__c,p.Id);
      }
     
      Map<String,List<String>>provinces = getCompanyProvinceMap();

      String sql = '{"data":" '+sql1+'"}';
      System.debug(sql);
        String url = Label.queryResposityURL;
        HttpRequest req = new HttpRequest();
        req.setBody(sql);
        req.setMethod('POST');
        req.setHeader('Content-Type','text/plain');
        req.setEndpoint(url);
        HttpResponse res = Utils.postRequest(req, 2);
      ///返回结果处理
        if (res.getStatusCode() == 200) {
          Map<String,Object> r = null;
              //如果是测试
                if(Test.isRunningTest()){
                  Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  resBody.put('result','{"result_msg":"查询成功！","result":1,"data":[{"invcode":"303537000000","oritaxprice":180000,"unitname":"北京迈克生物科技有限公司"}]}');
                    r =  resBody;
                }else{
                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                }
             System.debug(res.getBody());
          if(r.get('code') == 0 || r.get('code') == '0'){

              Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
              if( rs.get('result') == 1 ){
                  List<Object> datas =( List<Object>)rs.get('data');


                  Map<String,Price__c> prM = new Map<String,Price__c>();
                  Set<String> cms  = new Set<String>();
                  Set<String> ps  = new Set<String>();

                  for(Object o : datas){

                      Map<String,Object> mo = (Map<String,Object> )o ;
                      String inv = DataUtil.getStringValue(mo.get('invcode'));

                      String company =  DataUtil.getStringValue(mo.get('unitname'));
                      
                      if(inv== null || company == null || provinces.get(company) == null  )continue;
                       cms.add(company);
                      for (String province : provinces.get(company) ) {

                          Price__c p = new Price__c();
                          p.Product__c = productMap.get(inv);
                         
                          p.InstCost__c = DataUtil.getDecimalValue(mo.get('oritaxprice'));
                          p.Company__c = DataUtil.getStringValue(mo.get('unitname'));

                          p.Province__c = province;
                          String k = inv + company + province;
                          prM.put(k, p);
                          ps.add(province);

                      }

                   
                  }
                  //匹配
                  for (Price__c pr  :[select Id ,Company__c,Product__r.NCCode__c ,Province__c from Price__c where Product__r.NCCode__c in:nsets and Company__c in:cms  and Province__c in:ps ] ) {
                      
                       String k = pr.Product__r.NCCode__c + pr.Company__c+ pr.Province__c;
                      if(prM.containsKey(k))prM.get(k).Id = pr.Id;

                  }


                  SavePoint sp = Database.setSavepoint();
                  try{

                      if(!prM.isEmpty()) upsert prM.values();
                      if(prM.isEmpty()) return setResult(false ,'没有找到相关的数据!');
                      return setResult(true ,'获取成功!');

                  }catch(Exception e ){

                       Database.rollback(sp);
                       return setResult(false ,'保存失败:'+ e.getMessage());

                  }
                  



                    

            }else{
              return setResult(false ,String.valueOf(rs.get('result_msg')));
            }
          }else{
            return setResult(false ,String.valueOf(r.get('msg')));
          }
        }else{
          return setResult(false ,res.getBody());
        }


  }
 

	public static Map<String,String> setResult(Boolean isSuc ,String msg){
	Map<String,String> resultMap = new Map<String,String>();
		resultMap.put('msg', msg );
		resultMap.put('code', isSuc ? '1': '0');
		return resultMap;
	}


	@RemoteAction
	public static Map<String,String> getAccountFromNc(String nccodes){

		if(nccodes == null ) return setResult(false,'请输入客户编码');

		Boolean isMult = nccodes.contains(',') ;


		String sql1 = '   select * from v_custbaseinfo_esb where  ';

		if(isMult ){

			sql1 += ' custcode in '+	JSON.serialize(nccodes.trim().split(',')).replaceAll('"','\'').replace('[','(').replace(']',')') ; 
		}else{
			sql1 += ' custcode  = \''+nccodes.trim()+'\'';
		}
  		String sql = '{"data":" '+sql1+'"}';
     	System.debug(sql);
      	String url = Label.queryResposityURL;
      	HttpRequest req = new HttpRequest();
      	req.setBody(sql);
      	req.setMethod('POST');
      	req.setHeader('Content-Type','text/plain');
      	req.setEndpoint(url);
      	HttpResponse res = Utils.postRequest(req, 2);
      ///返回结果处理
        if (res.getStatusCode() == 200) {
        	Map<String,Object> r = null;
              //如果是测试
                if(Test.isRunningTest()){
                  Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  resBody.put('result','{"result_msg":"查询成功！","result":1,"data":[{"pk_cubasdoc":"0001C2100000000016OM","conaddr":"四川省成都市外南国学巷37号","custname":"四川大学华西医院","areaclcode":"10280104","custcode":"614854","fax1":null,"linkman1":null,"areaclname":"成都市武侯区","ts":"2018-11-26 12:17:17","taxpayerid":"12510000450756139Y","legalbody":null,"mobilephone1":null,"zdtype":"1","url":null,"email":null,"isgn":"Y","swkpfs":"0","zipcode":null,"phone1":"85422148"}]}');
                    r =  resBody;
                }else{
                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                }
        	if(r.get('code') == 0 || r.get('code') == '0'){
        		 Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
	            if( rs.get('result') == 1 ){
                  List<Object> datas =( List<Object>)rs.get('data');
                  List<UpsertAccountREST.AccountRestArgs> args = new List<UpsertAccountREST.AccountRestArgs>();
                  for(Object o : datas){

                    Map<String,Object> mo = (Map<String,Object> )o ;

                    UpsertAccountREST.AccountRestArgs arg1 = new UpsertAccountREST.AccountRestArgs();

                    arg1.rowno = String.valueOf(mo.get('rowno'));//
                    arg1.custcode = String.valueOf(mo.get('custcode')); //
                    arg1.custname = String.valueOf(mo.get('custname')); //
                    arg1.areaclcode = String.valueOf(mo.get('areaclcode')); //
                    arg1.areaclname = String.valueOf(mo.get('areaclname')); //
                    arg1.conaddr = String.valueOf(mo.get('conaddr')); //
                    arg1.zipcode = String.valueOf(mo.get('zipcode')); //
                    arg1.phone1 = String.valueOf(mo.get('phone1')); //
                    arg1.fax1 = String.valueOf(mo.get('fax1'));//
                    arg1.linkman1 = String.valueOf(mo.get('linkman1'));//
                    arg1.mobilephone1 = String.valueOf(mo.get('mobilephone1'));//
                    arg1.email = String.valueOf(mo.get('email'));//
                    arg1.url = String.valueOf(mo.get('url'));//
                    arg1.legalbody = String.valueOf(mo.get('legalbody'));//
                    arg1.taxpayerid = String.valueOf(mo.get('taxpayerid'));//
                    arg1.zdtype = String.valueOf(mo.get('zdtype'));
                    arg1.isgn = String.valueOf(mo.get('isgn'));
                    arg1.addrname = String.valueOf(mo.get('addrname'));
                    arg1.addrphone=String.valueOf(mo.get('addrphone'));
                    arg1.addrlinkman=String.valueOf(mo.get('addrlinkman')) ;
                    arg1.banktypename=String.valueOf(mo.get('banktypename')) ;
                    arg1.accname=String.valueOf(mo.get('accname')) ;//        
                    arg1.account =String.valueOf(mo.get('account')) ;//
                    arg1.accountname =String.valueOf(mo.get('accountname')) ;//
                    arg1.currtypename =String.valueOf(mo.get('currtypename')) ;//
                    arg1.pk_cubasdoc =String.valueOf(mo.get('pk_cubasdoc')) ;//
                    arg1.ts=String.valueOf(mo.get('ts'))  ;
                    arg1.swkpfs = String.valueOf(mo.get('swkpfs')) ; 
                    args.add(arg1);
                  }
                    RestReturnMessage message = UpsertAccountREST.upsertAccount(args);
                    return setResult(message.result == '1',message.result_msg);

            }else{
            	return setResult(false ,String.valueOf(rs.get('result_msg')));
            }
          }else{
          	return setResult(false ,String.valueOf(r.get('msg')));
          }
        }else{
        	return setResult(false ,res.getBody());
        }
	}
	@RemoteAction
	public static Map<String,String> getProductFromNc(String nccodes){

		if(nccodes == null ) return setResult(false,'请输入存货编码');

		Boolean isMult = nccodes.contains(',') ;

		String sql1 = '   select * from v_invbaseInfo_esb where  ';

		if(isMult ){

			sql1 += ' invcode in '+	JSON.serialize(nccodes.trim().split(',')).replaceAll('"','\'').replace('[','(').replace(']',')') ; 
		}else{
			sql1 += ' invcode  = \''+nccodes.trim()+'\'';
		}
  		String sql = '{"data":" '+sql1+'"}';
     	System.debug(sql);
      	String url = Label.queryResposityURL;
      	HttpRequest req = new HttpRequest();
      	req.setBody(sql);
      	req.setMethod('POST');
      	req.setHeader('Content-Type','text/plain');
      	req.setEndpoint(url);
      	HttpResponse res = Utils.postRequest(req, 2);
      ///返回结果处理
        if (res.getStatusCode() == 200) {
        	Map<String,Object> r = null;
              //如果是测试
                if(Test.isRunningTest()){
                  Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  resBody.put('result','{"result_msg":"查询成功！","result":1,"data":[{"sfaz":"否","invcode":"110100100001","dr":0,"own_corp":"迈克生物股份有限公司,山西迈克生物有限公司,上海迈可优生物科技有限公司,山东迈克生物科技有限公司,内蒙古迈克生物科技有限公司,北京迈克生物科技有限公司,新疆迈克宏康生物有限公司,迈克生物（广东）有限公司,迈克医疗电子有限公司,吉林迈克生物有限公司,迈克生物（湖北）有限公司,经销商公司,云南迈克科技有限公司,贵州迈克科技有限公司,四川省迈克实业有限公司,重庆征途科技有限公司","invclname":"迈克生化试剂肝功类","pk_invbasdoc":"0001C210000000000LA8","vpp":"迈克生物","ts":"2019-01-03 10:36:32","invclcode":"1101001","cpx":"生化","invmnecode":"CH0101001","invshortname":"TP","vmakefactory":"迈克生物股份有限公司","swjhdj":"8.2744","fjldw":null,"sealflag":"N","invtype":"TP:7170单","vpzwh":"川械注准20162400096","pzwhdate":"2021-05-10","bggsjhdj":"21.54","docname":"迈克生化试剂(开放)","invname":"总蛋白测定试剂盒（双缩脲法）","gssealflag":"N-MKSW,N-SXMK,N-SHMK,N-SDMK,N-NMMK,N-BJMK,N-XJMK,N-GDMK,N-MKDZ,N-JLMK,N-HBMK,N-ZJXS,N-YNMK,N-GZMK,N-MKSY,N-CQZT","zl":"240.00","taxitems":"商业（16 % ）","jldw":"盒","invspec":"试剂 60mL×4"}]}');
                    r =  resBody;
                }else{
                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                }
        	if(r.get('code') == 0 || r.get('code') == '0'){
        		 Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
	            if( rs.get('result') == 1 ){
                  List<Object> datas =( List<Object>)rs.get('data');
                  List<UpsertProductREST.ProductRestArgs> args = new List<UpsertProductREST.ProductRestArgs>();
                  for(Object o : datas){

                    Map<String,Object> mo = (Map<String,Object> )o ;

                    UpsertProductREST.ProductRestArgs arg1 = new UpsertProductREST.ProductRestArgs();
                    arg1.invcode = String.valueOf(mo.get('invcode'));//产品编码
                    arg1.invname = String.valueOf(mo.get('invname')); //产品名称
                    arg1.invspec = String.valueOf(mo.get('invspec')); //规格
                    arg1.invtype = String.valueOf(mo.get('invtype')); //型号
                    arg1.invshortname = String.valueOf(mo.get('invshortname')); //产品简称
                    arg1.invmnecode = String.valueOf(mo.get('invmnecode')); //助记码
                    arg1.invclcode = String.valueOf(mo.get('invclcode')); //存货分类编码
                    arg1.invclname = String.valueOf(mo.get('invclname')); //存货分类名称
                    arg1.jldw = String.valueOf(mo.get('jldw'));//计量单位
                    arg1.fjldw = String.valueOf(mo.get('fjldw'));//辅量单位
                    arg1.taxitems = String.valueOf(mo.get('taxitems'));//税目
                    arg1.cpx = String.valueOf(mo.get('cpx'));//产品线
                    arg1.vpp = String.valueOf(mo.get('vpp'));//品牌
                    arg1.vpzwh = String.valueOf(mo.get('vpzwh'));//批准文号
                    arg1.pzwhdate = String.valueOf(mo.get('pzwhdate'));//批准文号到期日
                    arg1.sealflag = String.valueOf(mo.get('sealflag'));
                    arg1.ts = String.valueOf(mo.get('ts'));
                    arg1.pk_invbasdoc = String.valueOf(mo.get('pk_invbasdoc'));
                    arg1.swjhdj=String.valueOf(mo.get('swjhdj'));
                    arg1.bggsjhdj=String.valueOf(mo.get('bggsjhdj')) ;

                    arg1.dr=String.valueOf(mo.get('dr')) ;
                    arg1.own_corp=String.valueOf(mo.get('own_corp')) ;//产品所属公司
        
                    arg1.zl =String.valueOf(mo.get('zl')) ;//装量

                    arg1.gssealflag =String.valueOf(mo.get('gssealflag')) ;//封存标记
                    arg1.docname =String.valueOf(mo.get('docname')) ;//预算大类
                    arg1.vmakefactory =String.valueOf(mo.get('vmakefactory')) ;//生产厂家
                    arg1.sfaz=String.valueOf(mo.get('sfaz'))  ;//是否安装
                    args.add(arg1);
                  }
                    RestReturnMessage message = UpsertProductREST.upsertProduct(args);
                    return setResult(message.result == '1',message.result_msg);

            }else{
            	return setResult(false ,String.valueOf(rs.get('result_msg')));
            }
          }else{
          	return setResult(false ,String.valueOf(r.get('msg')));
          }
        }else{
        	return setResult(false ,res.getBody());
        }
	}

}